package com.zmn.oms.task.listener;

import avro.shaded.com.google.common.collect.Lists;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Throwables;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.business.interfaces.order.DuplicateOrderBService;
import com.zmn.oms.business.interfaces.orderamount.OrderDiscountCalcBService;
import com.zmn.oms.business.interfaces.warranty.OrderWarrantyBService;
import com.zmn.oms.common.constant.MessageQueueTagConsts;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.model.dto.work.modify.DuplicateOrderDTO;
import com.zmn.oms.model.dto.work.modify.must.OrderStatementDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.statement.OrderStatementService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类描述：工单订阅监听
 *
 * @author lujia
 * @date 2018/11/30 16:53
 */
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
public class OrderWorkListener {

    private static final Logger logger = LoggerFactory.getLogger(OrderWorkListener.class);
    //
    // @Autowired
    // private SyncEsOrderWorkBService syncEsOrderWorkBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderWarrantyBService orderWarrantyBService;
    @Autowired
    private OrderStatementService orderStatementService;
    @Autowired
    private ElasticSearchDataSyncService elasticSearchDataSyncService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderDiscountCalcBService orderDiscountCalcBService;

    @Autowired
    private DuplicateOrderBService duplicateOrderBService;

    // @NacosValue(value = "${enable.mqsync:true}", autoRefreshed = true)
    // private boolean enableMqsync;


    // /**
    //  * 工单同步es消息监听
    //  * @param message
    //  */
    // @AliyunMQHandler(tags = MqTagConsts.ZMN_TOPIC_OMS_CHANGE_ORDER_WORK)
    // public void orderWorkChange(String message){
    //     if (!enableMqsync) {
    //         return;
    //     }else {
    //         logger.debug("mq sync enable;");
    //     }
    //
    //     // test
    //     if (Objects.equals(message, MqTopicConsts.MQ_TEST_MESSAGE)) {
    //         logger.debug("#mq#orderwork# recive test success");
    //         return;
    //     }
    //
    //     List<Long> orderIdList = null;
    //     try {
    //         orderIdList = JSON.parseArray(message, Long.class);
    //         if (orderIdList.size() >= 50) {
    //             logger.info("#mq#orderworkchange#2es#start");
    //         } else {
    //             logger.debug("#mq#orderworkchange#2es#start");
    //         }
    //         syncEsOrderWorkBService.sync(orderIdList);
    //         if (orderIdList.size() >= 50) {
    //             logger.info("#mq#orderworkchange#2es#end orderIdList.count:{}", orderIdList.size());
    //         } else {
    //             logger.debug("#mq#orderworkchange#2es#end orderIdList.count:{}", orderIdList.size());
    //         }
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         logger.error("#oms#orderworkchange#重建索引消费失败-", e);
    //         logger.error("#oms#orderworkchange#未同步工单列表[{}]", orderIdList);
    //         if (e instanceof SQLTransientConnectionException) {
    //             logger.error("数据库连接错误");
    //         }
    //     }
    // }

    // /**
    //  * 工单同步es消息监听 批量处理
    //  * @param message
    //  */
    // @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_CHANGE_ORDER_WORK_BATCH)
    // public void orderWorkChangeBatch(String message){
    //     // test
    //     if (Objects.equals(message, MqTopicConsts.MQ_TEST_MESSAGE)) {
    //         logger.debug("#mq#orderwork# recive test success");
    //         return;
    //     }
    //
    //     List<Long> orderIdList = null;
    //     try {
    //         orderIdList = JSON.parseArray(message, Long.class);
    //         if (orderIdList.size() >= 50) {
    //             logger.info("#mq#orderworkchange#2es#start");
    //         } else {
    //             logger.debug("#mq#orderworkchange#2es#start");
    //         }
    //         syncEsOrderWorkBService.sync(orderIdList);
    //         if (orderIdList.size() >= 50) {
    //             logger.info("#mq#orderworkchange#2es#end orderIdList.count:{}", orderIdList.size());
    //         } else {
    //             logger.debug("#mq#orderworkchange#2es#end orderIdList.count:{}", orderIdList.size());
    //         }
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         logger.error("#oms#orderworkchange#重建索引消费失败-", e);
    //         logger.error("#oms#orderworkchange#未同步工单列表[{}]", orderIdList);
    //         if (e instanceof SQLTransientConnectionException) {
    //             logger.error("数据库连接错误");
    //         }
    //     }
    // }

    /**
     * 添加投诉监听
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_ADD_COMPLAINT)
    public void addComplaint(String message){

        try {
            logger.debug("#mq#addcomplaint# recive message:{}", message);
            JSONObject data = JSON.parseObject(message);
            Long orderId = data.getLong("orderId");
            Long workId = data.getLong("workId");
            OrderWork orderWork = new OrderWork();
            orderWork.setOrderId(orderId);
            orderWork.setWorkId(workId);
            orderWork.setComplaintStatus(GlobalConsts.YES);
            orderWorkService.updateComplaintStatus(orderWork);
        } catch (Exception e) {
            logger.error("#mq#addcomplaint# {}", e.getMessage(), e);
        }
    }

    /**
     * 添加异常监听
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_ADD_ABNORMAL)
    public void addAbNormal(String message){

        try {
            logger.debug("#mq#addcomplaint# recive message:{}", message);
            JSONObject data = JSON.parseObject(message);
            Long orderId = data.getLong("orderId");
            Long workId = data.getLong("workId");
            OrderWork orderWork = new OrderWork();
            orderWork.setOrderId(orderId);
            orderWork.setWorkId(workId);
            orderWork.setAbnormalStatus(GlobalConsts.YES);
            orderWorkService.updateAbnormalStatus(orderWork);
        } catch (Exception e) {
            logger.error("#mq#addabnormal# {}", e.getMessage(), e);
        }
    }

    /**
     * 添加修改保修时长监听（已废弃）
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_UPDATE_WARRANTY_MONTH)
    public void updateWarrantyMonth(String message){

        try {
            logger.debug("#mq#updateWarrantyMonth# recive message:{}", message);
            JSONObject data = JSON.parseObject(message);
            Long orderId = data.getLong("orderId");
            Integer month = data.getInteger("month");
            orderWarrantyBService.updateWarrantyMonth(orderId, month);
        } catch (Exception e) {
            logger.error("#mq#updateWarrantyMonth# {}", e.getMessage(), e);
        }
    }

    /**
     * 结算监听
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_CHANNEL_STATEMENT)
    public void channelStatement(String message){
        try {
            logger.debug("#mq#channelStatement# recive message:{}", message);
            List<OrderStatementDTO> channelStatementDTOList = JSON.parseArray(message, OrderStatementDTO.class);
            channelStatementDTOList.forEach(e -> {
                orderStatementService.updateStatement(e);
            });

            // 分割同步es
            logger.debug("#mq#channelStatement# 开始同步es.....");
            List<Long> orderIdList = channelStatementDTOList.stream().map(OrderStatementDTO::getOrderId).collect(Collectors.toList());
            List<List<Long>> partitionOrderList = Lists.partition(orderIdList, 100);
            partitionOrderList.forEach(e -> {
                logger.debug("#mq#channelStatement# 开始同步es {}", e.toString());
                elasticSearchDataSyncService.syncWorkIndex(e);
            });
        } catch (Exception e) {
            logger.error("#mq#channelStatement# {}", e.getMessage(), e);
        }
    }

    /**
     * 结算监听
     * @param message
     */
    @AliyunMQHandler(tags = MessageQueueTagConsts.ERP_SP_SETTLE)
    public void spStatement(String message){
        try {
            logger.info("#mq#spStatement# recive message:{}", message);
            List<OrderStatementDTO> spStatementDTOList = JSON.parseArray(message, OrderStatementDTO.class);
            spStatementDTOList.forEach(e -> {
                orderStatementService.updateStatement(e);
            });

            // 分割同步es
            logger.info("#mq#spStatement# 开始同步es.....");
            List<Long> orderIdList = spStatementDTOList.stream().map(OrderStatementDTO::getOrderId).collect(Collectors.toList());
            List<List<Long>> partitionOrderList = Lists.partition(orderIdList, 100);
            partitionOrderList.forEach(e -> {
                logger.info("#mq#spStatement# 开始同步es {}", e.toString());
                elasticSearchDataSyncService.syncWorkIndex(e);
            });
        } catch (Exception e) {
            logger.error("#mq#spStatement# {}", e.getMessage(), e);
        }
    }

    /**
     * 计价器有效无效监听
     * @param message
     */
    @AliyunMQHandler(tags = MessageQueueTagConsts.PERF_QUOTATION_STATUS)
    public void quotationStatus(String message){
        logger.info("#mq#quotationStatus# recive message:{}", message);
        try {
            Long workId = Long.valueOf(message);
            elasticSearchDataSyncService.syncWorkIndex(workId);
        } catch (Exception e) {
            logger.error("#mq#quotationStatus# {}", e.getMessage(), e);
        }
    }

    /**
     * 优惠售价监听
     * @param message
     */
    @AliyunMQHandler(tags = MessageQueueTagConsts.OMS_THIRD_COUPON_SALE_PRICE)
    public void discountSellAmount(String message){
        logger.info("#mq#discountSellAmount# recive message:{}", message);
        JSONObject data = JSON.parseObject(message);
        Long orderId = data.getLong("orderId");
        Integer cityId = data.getInteger("cityId");
        Integer channelId = data.getInteger("channelId");
        String itemCode = data.getString("itemCode");
        logger.info("获取售价--->{}", orderId);
        orderDiscountCalcBService.getThirdSellAmount(orderId, cityId, channelId, itemCode);
    }


    /**
     *  疑似重复单监听
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.SUSPECTED_DUPLICATE_ORDER)
    public void suspectedDuplicateOrder(String message) {
        logger.info("OmsOrderWorkTrackListener.suspectedDuplicateOrder message={}", message);
        try {
            DuplicateOrderDTO duplicateOrderDTO = JSON.parseObject(message, DuplicateOrderDTO.class);
            duplicateOrderBService.handleSuspectedDuplicateTrack(duplicateOrderDTO);
        } catch (Exception ex) {
            logger.error("OmsOrderWorkTrackListener.suspectedDuplicateOrder error={}", Throwables.getStackTraceAsString(ex));
        }
    }
}
